﻿using Api1.Service;
using Api1.Util;
using Newtonsoft.Json;
using ocmctr;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Xml;
using zwWitLink.Util;

namespace Api1
{
    public partial class MainTab : Form
    {

        public static MainTab instance = null;
        public static UmfCtr umf = null;
        ToolTip tip = new ToolTip();
        public MainTab()
        {
            InitializeComponent();
            loading();
            umf = zwForm._test_get_umf();
            tip.BackColor = Color.Red;
            
            tip.SetToolTip(SetWaterPump, "setWaterPump(int type, int count, int munute)");
            tip.SetToolTip(smartClearCup, "smartClearCup(bool isRent)");
            tip.SetToolTip(ReadSmartCupNo, "ReadSmartCupNo(ref card_no)");
            tip.SetToolTip(staffCardSet, "staffCardSet(String auth)");
            tip.SetToolTip(WriteAuth, "WriteAuth(String auth)");
            tip.SetToolTip(isRentCup,"isRentCup()");
            tip.SetToolTip(ReadNoNumber, "ReadNoNumber()"); 
            tip.SetToolTip(QueryCard, "QueryCard(String card_no)");
            tip.SetToolTip(StoreCup, "StoreCup(int is_rent)  1租用柜， 0临时柜");

        }
        public void loading() {
            textBox1.Text = AKApiService.url;
            textBox17.Text= AKApiService.url_get_contract_info;
            textBox2.Text = AKApiService.brand_code;
            textBox3.Text = AKApiService.club_id;
            textBox5.Text = AKApiService.key;

            textBox15.Text = AKApiService.url;
            textBox18.Text = AKApiService.url_check_in;
            textBox7.Text = AKApiService.club_id;
            textBox10.Text = AKApiService.key;
            textBox6.Text = AKApiService.brand_code;

            textBox16.Text = AKApiService.url;
            textBox19.Text = AKApiService.url_check_out;
            textBox11.Text = AKApiService.brand_code;
            textBox12.Text = AKApiService.club_id;
            textBox14.Text = AKApiService.key;

            ip_text.Text = OperateIniFile.ReadIniData("Config", "host","");
            is_slave.Text = OperateIniFile.ReadIniData("Config", "is_slave", "0").Equals("0") ? "主机" : "从机";
            is_debug.Text = OperateIniFile.ReadIniData("DB", "host", "false").Equals("false") ? "关闭" : "开启";
            browser.Text = OperateIniFile.ReadIniData("Config", "Browser", browser.Text);
            IsBlackImage.Text = OperateIniFile.ReadIniData("Config", "IsBlackImage", "0");
            lockvertion.Text = OperateIniFile.ReadIniData("Config", "LockVersion", "0");
        }

        private void card_no_TextChanged(object sender, EventArgs e)
        {

        }

        private void btn_in_Click(object sender, EventArgs e)
        {
            String cards = card_no.Text.ToString();
            if (cards.Trim().Length < 2)
            {
                result.Text = "请输入10位卡号";
                return;
            }
            else
            {
                result.Text = "";
                result.AppendText("开始时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                var re = ApiService.inSwipeCard(cards, "01", cabinet_no.Text);
                result.AppendText("\r\n结束时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));

                result.AppendText("flag:" + re["flag"] + "\r\n");
                result.AppendText("data:" + re["data"] + "\r\n");
                result.AppendText("is_open:" + re["is_open"] + "\r\n");
                result.AppendText("varify_type:" + re["varify_type"] + "\r\n");
                if (re["member"] != null)
                {
                    var member = (Dictionary<String, String>)re["member"];
                    result.AppendText("name:" + member["name"] + "\r\n");
                    result.AppendText("end_date:" + member["end_date"] + "\r\n");
                    result.AppendText("surplus_num:" + member["surplus_num"] + "\r\n");
                }
            }
        }

        private void btn_out_Click(object sender, EventArgs e)
        {
            String cards = card_no.Text.ToString();
            if (cards.Trim().Length < 2)
            {
                result.Text = "请输入10位卡号";
                return;
            }
            else
            {
                var re = ApiService.outSwipeCard(cards, "02", cabinet_no.Text,Convert.ToInt32(is_store.Text));
                result.Text = "";
                result.AppendText("flag:" + re["flag"] + "\r\n");
                result.AppendText("data:" + re["data"] + "\r\n");
                result.AppendText("is_open:" + re["is_open"] + "\r\n");
                result.AppendText("varify_type:" + re["varify_type"] + "\r\n");
            }
        }

        private void btn_v1_Click(object sender, EventArgs e)
        {
            String cards = card_no.Text.ToString();
            if (cards.Trim().Length < 2)
            {
                result.Text = "请输入10位卡号";
                return;
            }
            else
            {
                int i = new Random().Next(0, 10) % 2;
                var flag =i==1?true:false;
                result.Text = "";
                result.AppendText("开始时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                var re=ApiService.swipeFingerPrintResult(cards, flag, "01");
                result.AppendText("\r\n结束时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));

                result.AppendText("flag:" + re["flag"] + "\r\n");
                result.AppendText("data:" + re["data"] + "\r\n");
                result.AppendText("is_open:" + re["is_open"] + "\r\n");
                result.AppendText("varify_type:" + re["varify_type"] + "\r\n");
                if (re["member"] != null) {
                    var member = (Dictionary<String,String> )re["member"];
                    result.AppendText("name:" + member["name"] + "\r\n");
                    result.AppendText("end_date:" + member["end_date"] + "\r\n");
                    result.AppendText("surplus_num:" + member["surplus_num"] + "\r\n");
                    result.AppendText("cur_month_times:" + member["cur_month_times"] + "\r\n");
                    result.AppendText("cur_month_count:" + member["cur_month_count"] + "\r\n");
                }
                result.AppendText("模拟比对：" + flag);
            }
        }

        private void btn_v2_Click(object sender, EventArgs e)
        {
            String cards = card_no.Text.ToString();
            if (cards.Trim().Length < 2)
            {
                result.Text = "请输入10位卡号";
                return;
            }
            else
            {
                String innerdoorstr = innerdoor.Text.ToString();
                if (String.IsNullOrWhiteSpace(innerdoorstr))
                {
                    innerdoorstr = "0";
                }
                else {
                    innerdoorstr=innerdoorstr.Trim();
                }
                var re = ApiService.innerDoorSwipe(cards, innerdoorstr);
                result.Text = "";

                result.AppendText("flag:" + re["flag"] + "\r\n");
                result.AppendText("data:" + re["data"] + "\r\n");
                result.AppendText("is_open:" + re["is_open"] + "\r\n");
                result.AppendText("varify_type:" + re["varify_type"] + "\r\n");
                if (re["member"] != null)
                {
                    var member = (Dictionary<String, String>)re["member"];
                    result.AppendText("name:" + member["name"] + "\r\n");
                    result.AppendText("end_date:" + member["end_date"] + "\r\n");
                    result.AppendText("surplus_num:" + member["surplus_num"] + "\r\n");
                }
            }
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void tabPage4_Click(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click_1(object sender, EventArgs e)
        {

        }

        private void label11_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {   
            richTextBox1.Text = AKApiService.GetInstance().TestGetContractInfo(textBox4.Text);
        }

        private void button2_Click(object sender, EventArgs e)
        {
             String time= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
             String time1=AKApiService.GetInstance().TestCheckIn(textBox8.Text, textBox9.Text);
             String time2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
            richTextBox2.Text = time + "---------" + time1 + "------------" + time2;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            richTextBox3.Text = AKApiService.GetInstance().TestCheckOut(textBox13.Text);
        }

        private void label22_Click(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        public bool CheckUrlVisit(string url)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://" + url);
                req.Timeout = 2000;
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    resp.Close();
                    return true;
                }
            }
            catch (WebException)
            {
                return false;
            }

            return false;

        }

        private void button4_Click(object sender, EventArgs e)
        {

            IPAddress ips;
            if (!IPAddress.TryParse(ip_text.Text, out ips))
            {
                MessageBox.Show("ip格式错误");
                return;
            }
            //PingReply reply = new Ping().Send(ip_text.Text);
            //if (reply.Status != IPStatus.Success)
            //{
            //    MessageBox.Show("无法ping 通服务器ip");
            //    return;
            //}
            if (!CheckUrlVisit(ip_text.Text))
            {
                MessageBox.Show("无法链接主机");
                return;

            }
            else
            {
                MessageBox.Show("链接成功");
                return;

            }
        }

        private void button5_Click(object sender, EventArgs e)
        {

            IPAddress ips;
            if (!IPAddress.TryParse(ip_text.Text, out ips))
            {
                MessageBox.Show("ip格式错误");
                return;
            }
            //PingReply reply = new Ping().Send(ip_text.Text);
            //if (reply.Status != IPStatus.Success)
            //{
            //    MessageBox.Show("无法ping 通服务器ip");
            //    return;
            //}
            if (!CheckUrlVisit(ip_text.Text))
            {
                MessageBox.Show("无法链接主机");
                return;
            }
            OperateIniFile.WriteIniData("Config", "host", ip_text.Text);
            OperateIniFile.WriteIniData("Config", "is_slave", is_slave.Text.Equals("主机")?"0":"1");
            OperateIniFile.WriteIniData("DB", "debug", is_debug.Text.Equals("开启") ? "true" : "false");
            OperateIniFile.WriteIniData("Config", "Browser", browser.Text);
            OperateIniFile.WriteIniData("Config", "IsBlackImage", IsBlackImage.Text);
            OperateIniFile.WriteIniData("Config", "LockVersion", lockvertion.Text);
            MessageBox.Show("保存成功");
           
        }

        private void MainTab_FormClosed(object sender, FormClosedEventArgs e)
        {
            instance = null;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            OperateIniFile.WriteIniData("ANKE", "Url", textBox1.Text);
            OperateIniFile.WriteIniData("ANKE", "BrandCode", textBox2.Text);
            OperateIniFile.WriteIniData("ANKE", "Key", textBox5.Text);
            OperateIniFile.WriteIniData("ANKE", "ClubID", textBox3.Text);
            OperateIniFile.WriteIniData("ANKE", "CardNo", textBox4.Text);
            MessageBox.Show("保存成功");

        }

        private void label26_Click(object sender, EventArgs e)
        {

        }

        private void label27_Click(object sender, EventArgs e)
        {

        }

        private void button8_Click(object sender, EventArgs e)
        {
            //清空
            richTextBox4.Text = "";
            richTextBox5.Text = "";
            String images = this.images.Text.Trim();
            if (String.IsNullOrWhiteSpace(images))
            {
                this.images.Focus();
                MessageBox.Show("请输入图片路径");
                return;
            }
            images = images.Replace(" ", "");
            String[] array=images.Split(',');
            foreach (var item in array)
            {
                if (File.Exists(@item))
                {
                    String code1=  zwForm.GetDetect(@item)[0];
                    if (String.IsNullOrWhiteSpace(code1))
                    {
                        richTextBox4.Text += ",0";
                    }
                    else {
                        richTextBox4.Text += ",1";
                    }

                    String pre_name = item.Split('.')[0];
                    String sub_name = item.Split('.')[1];
                    String new_file_name = pre_name + "_." + sub_name;
                    ImageConver.GrayImage(new Bitmap(Image.FromFile(item)), 1).Save(new_file_name);

                    String code2 = zwForm.GetDetect(@new_file_name)[0];
                    if (String.IsNullOrWhiteSpace(code2))
                    {
                        richTextBox5.Text += ",0";
                    }
                    else
                    {
                        richTextBox5.Text += ",1";
                    }
                }
                else {
                    richTextBox4.Text += ",0";
                    richTextBox5.Text += ",0";
                }
            }
            MessageBox.Show("彩图转黑白图片转换成功"); 
        }

        private void button7_Click(object sender, EventArgs e)
        {
            results.Text = "";
            String source_str = sources.Text.Trim();
            String target_str = targets.Text.Trim();
            if (String.IsNullOrWhiteSpace(source_str)) {
                MessageBox.Show("请输入原图片路径");
                return;
            }
            if (String.IsNullOrWhiteSpace(target_str))
            {
                MessageBox.Show("请输入目标图片路径");
                return;
            }
            if (!File.Exists(@source_str)) {
                MessageBox.Show("原图片不存在");
                return;
            }
            if (!File.Exists(target_str))
            {
                MessageBox.Show("目标图片");
                return;
            }
            try
            {
              Object o=  zwForm.TestFaceMath(zwForm.TestFaceDetect(source_str), zwForm.TestFaceDetect(target_str));
                if (o == null)
                {
                    results.Text = "0";
                }
                else {
                    results.Text = o.ToString();
                }
                                
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
          
        }

      

        private void button10_Click(object sender, EventArgs e)
        {
           MessageBox.Show("当前读卡状态："+zwForm._test_focus_start());
        }

        private void button11_Click(object sender, EventArgs e)
        {
            MessageBox.Show("当前读卡状态"+zwForm._test_focus_stop() + "");
        }
        /// <summary>
        /// 省级会员信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button9_Click(object sender, EventArgs e)
        {
            ApiServiceImpl.UpdateMember();
        }
        /// <summary>
        /// 升级员工信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button12_Click(object sender, EventArgs e)
        {

        }

        private void button12_Click_2(object sender, EventArgs e)
        {
            if(!zwForm.autorun)
            zwForm._test_focus_start();
        }

        private void button13_Click_1(object sender, EventArgs e)
        {
            zwForm._test_focus_stop();
        }

        private void isRentCup_Click(object sender, EventArgs e)
        {
            richTextBox7.Text = umf.isRentCup() + "";
        }

        private void writeAuth_Click(object sender, EventArgs e)
        {
            richTextBox7.Text = umf.WriteAuth(getParams()[0])+"";
        }

        private void staffCardSet_Click(object sender, EventArgs e)
        {
          richTextBox7.Text=umf.staffCardSet(getParams()[0]);
        }
        public String[] getParams() {
            String paramstr=richTextBox6.Text;
            if (String.IsNullOrWhiteSpace(paramstr)) {
                return new string[]{ ""};
            }
            paramstr=paramstr.Replace(" ","");
            return paramstr.Split(',');
        }

        private void readSmartCupNo_Click(object sender, EventArgs e)
        {
            String res= umf.ReadSmartCupNo(); 
            richTextBox7.Text = res;
        }

        private void SetWaterPump_Click(object sender, EventArgs e)
        {
            if (getParams().Length < 3) {
                MessageBox.Show("参数错误");
                return;
            }
            try
            {
                richTextBox7.Text = umf.setWaterPump(Int32.Parse(getParams()[0]), Int32.Parse(getParams()[01]), Int32.Parse(getParams()[2]));
            }
            catch (Exception)
            {

                throw;
            }
            
        }

        private void smartClearCup_Click(object sender, EventArgs e)
        {
            
            richTextBox7.Text = umf.smartClearCup(Convert.ToBoolean(getParams()[0])) +"";
        }

        private void ReadNoNumber_Click(object sender, EventArgs e)
        {
            richTextBox7.Text = umf.ReadNoNumber();
        }

        private void QueryCard_Click(object sender, EventArgs e)
        {
            richTextBox7.Text = umf.QueryCard(getParams()[0]);
        }

        private void StoreCup_Click(object sender, EventArgs e)
        {  
            richTextBox7.Text = umf.StoreCup(Convert.ToInt32(getParams()[0]))+"";
        }
    }
}
